package com.woniu.springsecurity.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.springsecurity.response.ResponseResult;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CustomAccessDeniedExceptionHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        ResponseResult<Object> result = new ResponseResult<>(HttpStatus.FORBIDDEN.value(), "权限不足", null);
        //设置响应头
        response.setContentType("application/json;charset=UTF-8");
        //写数据
        response.getWriter().write(new ObjectMapper().writeValueAsString(result));
        //刷新缓冲区
        response.getWriter().flush();
        //关闭流
//        response.getWriter().close();
    }
}
